package com.klikmee.sms.core.base.creators;

import java.text.MessageFormat;
import java.util.List;

import org.apache.log4j.Logger;

import com.klikmee.sms.core.base.util.States;
import com.klikmee.sms.core.model.BulkMessage;
import com.klikmee.sms.core.model.Provider;
import com.klikmee.sms.core.model.ServiceChargingCategory;

/**
 * Bulk creator which produces only single bulk messages (ignoring other
 * recipients if any)
 * 
 * @author makcro
 * 
 */
public class SingleBulkMessageCreatorImpl extends SimpleBulkMessageCreatorImpl {

	// logger instance
	private Logger	logger	= Logger.getLogger( SingleBulkMessageCreatorImpl.class );

	/**
	 * Override that creates single bulk message (to first receiver in the list, ignoring others if aby)
	 */
	@Override
	public int createBulkMessage(String text, List<String> receiverIds, String signatureText, ServiceChargingCategory serviceChargingCategory) {

		// verify phone number
		String singleReceiver = receiverIds.get( 0 );
		Provider provider = resolveProvider( singleReceiver );
		if (provider == null) {

			logger.warn( MessageFormat.format( "Invalid phone number detected during sending bulk message [{0}]", singleReceiver ));
		}

		// continue with sending bulk message
		BulkMessage bulkMessage = new BulkMessage();
		bulkMessage.setText( text );
		bulkMessage.setSenderId( signatureText );
		bulkMessage.setToNumber( singleReceiver );
		bulkMessage.setProvider( provider );
		bulkMessage.setChargingCategory( serviceChargingCategory );

		bulkMessage.setState( States.BulkMessage.WAITING_TO_BE_SENT );

		// store bulk message into database
		bulkMessageDAO.create( bulkMessage );
		// submit message to bulk queue
		core.enqueueBulkMessage( bulkMessage );
		// increment count

		logger.debug( MessageFormat.format( "Created bulk message with id [{0}]", bulkMessage.getId() ) );

		// return id safely casted to integer
		return (int) Math.min( Integer.MAX_VALUE, bulkMessage.getId() );
	}
}
